package com.example.examsystem.security;

import com.example.examsystem.model.Role;
import com.example.examsystem.model.User;
import com.example.examsystem.model.Permission;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户主体类
 * 实现Spring Security的UserDetails接口
 */
@Data
@AllArgsConstructor
@Builder
public class UserPrincipal implements UserDetails {

    /**
     * 用户ID
     */
    private Long id;
    /**
     * 用户名
     */
    private String username;
    /**
     * 用户密码
     */
    @JsonIgnore
    private String password;
    /**
     * 用户邮箱
     */
    private String email;
    /**
     * 真实姓名
     */
    private String fullName;
    /**
     * 用户权限列表
     */
    private Collection<? extends GrantedAuthority> authorities;
    /**
     * 用户是否启用
     */
    private boolean enabled;
    /**
     * 用户是否锁定
     */
    private boolean accountNonLocked;
    
    /**
     * 从User实体创建UserPrincipal
     */
    public static UserPrincipal create(User user, Set<Role> roles, Set<Permission> permissions) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        // 添加角色权限
        roles.stream()
            .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
            .forEach(authorities::add);
        
        // 添加功能权限
        permissions.stream()
            .map(permission -> new SimpleGrantedAuthority(permission.getResource() + ":" + permission.getAction()))
            .forEach(authorities::add);
        
        return UserPrincipal.builder()
                .id(user.getId())
                .username(user.getUsername())
                .password(user.getPassword())
                .email(user.getEmail())
                .fullName(user.getFullName())
                .authorities(authorities)
                .enabled(user.getEnabled())
                .accountNonLocked(!user.getAccountLocked())
                .build();
    }
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }
    
    @Override
    public String getPassword() {
        return password;
    }
    
    @Override
    public String getUsername() {
        return username;
    }
    
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    
    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }
    
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    
    @Override
    public boolean isEnabled() {
        return enabled;
    }
}




